package io.alvin.ch03;

import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * Fork/Join框架样例
 *
 * 注：使用Fork/Join时可能出现两种情况：
 * 1）系统内的线程数量越积越多，导致性能严重下降；
 * 2）函数的调用层次变得很深，最终导致栈溢出。
 *
 * Created by Alvin on 2017/7/11.
 */
public class ForkJoinTaskDemo extends RecursiveTask<Long> {

    private static final int THRESHHOLD = 10000;
    private long start;
    private long end;

    public ForkJoinTaskDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }

    /**
     * The main computation performed by this task.
     *
     * @return the result of the computation
     */
    @Override
    protected Long compute() {
        long sum = 0;
        boolean canCompute = (end - start) < THRESHHOLD;
        if(canCompute) {
            for(long i = start;i <= end;i++) {
                sum += i;
            }
        } else {
            // 分成100个小任务
            long step = (start + end) / 100;
            ArrayList<ForkJoinTaskDemo> subTasks = new ArrayList<ForkJoinTaskDemo>();
            long pos = start;
            for(int i = 0; i < 100; i++) {
                long lastOne = pos + step;
                if (lastOne > end) lastOne = end;
                ForkJoinTaskDemo subTask = new ForkJoinTaskDemo(pos,lastOne);
                pos += step + 1;
                subTasks.add(subTask);
                subTask.fork();
            }
            for (ForkJoinTaskDemo t : subTasks) {
                sum += t.join();
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        // 建立Fork/Join线程池
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTaskDemo task = new ForkJoinTaskDemo(0, 200000L);
        ForkJoinTask<Long> result = forkJoinPool.submit(task);
        try {
            long res = result.get();
            System.out.println("sum=" + res);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
